import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useState, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addHistory, getSuggestion } from '@/store/action/search'
import { RootState } from '@/store'
import DOMPurify from 'dompurify'
import { Toast } from 'antd-mobile'
import history from '@/utils/history'

export default function Search() {

  const [value, setValue] = useState('')

  const dispatch = useDispatch()

  const { list, searchHistory } = useSelector((state: RootState) => state.search)

  const valueRef = useRef(0)

  const handlValue = (value: string) => {
    setValue(value)
    if (value.trim() === '') return
    window.clearTimeout(valueRef.current)
    valueRef.current = window.setTimeout(() => {
      dispatch(getSuggestion(value))
    }, 500);
  }

  // 替换高亮字符串
  const highlightFu = (str: string, val: string) => {
    // return str.replaceAll(val, `<span>${val}</span>`)
    return str.replaceAll('FU', `<span>FU</span>`)
  }

  // 点击搜索
  const handlSearch = () => {
    if (value.trim() === '') return Toast.show({ content: '不能为空', maskClassName: 'and_toast_err' })
    dispatch(addHistory(value))
    setValue('')
    history.push(`/search/result/${value}`)
  }

  // 点击清除全部
  const handlClearAll = () => {
    // 清除仓库数据和本地数据
    dispatch(addHistory('',true))
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar right={<span className='search-text' onClick={() => handlSearch()}>搜索</span>}>
        <div className='navbar-search'>
          <Icon type='iconbtn_search' className='icon-search' />

          <div className='input-wrapper'>
            {/* 输入框 */}
            <input onKeyUp={(e) => {
              if (e.key === 'Enter') handlSearch()
            }}
              value={value} onChange={(e) => handlValue(e.target.value)} type='text' placeholder='请输入关键字搜索' />

            {/* 清空输入框按钮 */}
            <Icon type='iconbtn_tag_close' className='icon-close' onClick={() => setValue('')} />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      <div className='history' hidden={!!value}>
        <div className='history-header'>
          <span>搜索历史</span>
          <span onClick={() => handlClearAll()}>
            <Icon type='iconbtn_del' />
            清除全部
          </span>
        </div>

        <div className='history-list'>
          {searchHistory.map((item, index) => (
            <span className='history-item' key={index}>
              {item}<span className='divider'></span>
            </span>
          ))}


        </div>
      </div>

      {/* 搜素建议结果列表 */}
      <div className='search-result' hidden={!value}>

        {list.map((item, index) => (
          <div className='result-item' key={index}>
            <Icon className='icon-search' type='iconbtn_search' />
            <div className='result-value' dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(highlightFu(item, value)) }}>

            </div>
          </div>
        ))}

      </div>
    </div>
  )
}
